package org.opens.javaskill;

import org.junit.Test;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

public class TimeFormat {

    public static Date getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    public static Date getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        cal.set(Calendar.HOUR, 23);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    @Test
    public void test1() {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getLastDayOfMonth(2019, 12)));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getFirstDayOfMonth(2019, 12)));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getLastDayOfMonth(2019, 12)));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getFirstDayOfMonth(2019, 12)));
    }

    @Test
    public void test2() {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getBeginDayOfWeek()));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getEndDayOfWeek()));
    }

    //获取本周的开始时间
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.add(Calendar.DATE, 2 - dayofweek);
        return cal.getTime();
    }

    //获取本周的结束时间
    public static Date getEndDayOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfWeek());
        cal.set(Calendar.HOUR, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return cal.getTime();
    }

    /**
     * 功能:
     * 将1.8新增的Duration类解析为秒.
     */
    @Test
    public void usageDuration() {
        Duration duration = Duration.parse("PT30M");
        System.out.println(duration.get(ChronoUnit.SECONDS));
    }

}
